package com.ws.soa.consumer.filter;

import com.alibaba.fastjson.JSONObject;
import com.ws.soa.consumer.service.SessionStorageClientService;
import com.ws.soa.consumer.session.UserSessionStorage;

import org.springframework.context.annotation.Configuration;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * TokenFilter
 *
 * @author marvel
 */
@Configuration
public class TokenFilter implements Filter {

    @Resource
    private SessionStorageClientService sessionStorageClientService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException,
                                                                                                            ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        boolean isContainsLogin = request.getRequestURL().toString().contains("/login");
        // 放行忘记密码的链接
        boolean isRegister = request.getRequestURL().toString().contains("/register");
/*        // 放行获取验证码的链接
        boolean isVerficationCode = request.getRequestURL().toString().contains("/verification/code");*/

        // 从 redis 里面获取用户
        UserSessionStorage sessionStorage = this.sessionStorageClientService.getUserSessionStorage(request);

        // 如果获取到了则放行
        if (isContainsLogin || isRegister || sessionStorage != null) {
            // 放行
            chain.doFilter(request, response);
        } else {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            JSONObject json=new JSONObject();
            json.put("code", -1);
            response.getWriter().println(json.toString());
        }
    }

    @Override
    public void destroy() {}


}